package com.jxpanda.plugin.initializr.task

import com.baomidou.mybatisplus.generator.AutoGenerator
import com.baomidou.mybatisplus.generator.config.OutputFile
import com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder
import com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine
import com.fasterxml.jackson.dataformat.yaml.YAMLMapper
import com.jxpanda.plugin.initializr.config.AutoGeneratorBuilder
import com.jxpanda.plugin.initializr.config.Config
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.InputFile
import org.gradle.api.tasks.TaskAction
import java.io.File

open class GeneratorTask : DefaultTask() {

    @get:InputFile
    val configFile: File = File("${project.projectDir.path}/init.yml")

    open fun before(autoGenerator: AutoGenerator): AutoGenerator {
        return autoGenerator
    }

    private fun templateEngine(): AbstractTemplateEngine {
        return object : FreemarkerTemplateEngine() {
            override fun init(configBuilder: ConfigBuilder): FreemarkerTemplateEngine {
                val xmlPath = configBuilder.pathInfo[OutputFile.xml]
                if (!xmlPath.isNullOrBlank()) {
                    val pathSplit = xmlPath.split("src${File.separator}main")
                    configBuilder.pathInfo[OutputFile.xml] = "${pathSplit[0]}src${File.separator}main${File.separator}resources${File.separator}mapper"
                }
                return super.init(configBuilder)
            }
        }
    }

    @TaskAction
    fun execute() {
        val autoGenerator = AutoGeneratorBuilder.builder()
                .projectPath(project.projectDir.path)
                .config(YAMLMapper().readValue(configFile, Config::class.java))
                .build()
        before(autoGenerator).execute(templateEngine())
        after()
    }

    open fun after() {

    }

}